package com.youxin.logprocess.bean;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import org.apache.log4j.Logger;

import com.youxin.foundation.utils.RegexUtils;
import com.youxin.foundation.utils.StringUtils;
/**
 * Nginx bean
 * @author yingde.cao
 *
 */
public class NginxBean {
	protected static Logger logger = Logger.getLogger(NginxBean.class);
	private NginxRequestBean requestBean;
	private String remoteAddr,timeLocal,request,httpReferer,httpXforwardedFor;
	private Date timeLocalDate;
	private String host;
	
	public String getHost() {
		return host;
	}

	public void setHost(String host) {
		this.host = host;
	}


	public NginxRequestBean getRequestBean() {
		return requestBean;
	}


	public String getRemoteAddr() {
		return remoteAddr;
	}

	public void setRemoteAddr(String remoteAddr) {
		this.remoteAddr = remoteAddr;
	}

	public String getTimeLocal() {
		return timeLocal;
	}

	public void setTimeLocal(String timeLocal) {
		this.timeLocal = timeLocal;
		convertTimeLocal();
	}

	public String getRequest() {
		return request;
	}

	public void setRequest(String request) {
		this.request = request;
		convertRequestBean();
	}

	public String getHttpReferer() {
		return httpReferer;
	}

	public void setHttpReferer(String httpReferer) {
		this.httpReferer = httpReferer;
	}

	public String getHttpXforwardedFor() {
		return httpXforwardedFor;
	}

	public void setHttpXforwardedFor(String httpXforwardedFor) 
	{
		this.httpXforwardedFor = httpXforwardedFor;
	}
	
	public Date getTimeLocalDate() {
		return timeLocalDate;
	}
	/**
	 * 时间转换 25/Oct/2017:07:44:24 -0700
	 */
	private void convertTimeLocal() {		
		try {
			SimpleDateFormat formatter = new SimpleDateFormat("dd/MMM/yyyy:HH:mm:ss Z", Locale.ENGLISH);
			this.timeLocalDate = formatter.parse(timeLocal);
		} catch (Exception e) {
			logger.error(timeLocal + "转换错误", e);
		}
	}

	/**
	 * GET /favicon.ico HTTP/1.1
	 * 转换为Request Bean
	 */
	private void convertRequestBean(){
		try {
			String regex = "(\\w+)\\s+([^\\s]+)\\s+(([^\\s]+))";			
			NginxRequestBean tbean=RegexUtils.match(regex, this.request, (matcher,success)->{
				if(success)
				{
					NginxRequestBean bean=new NginxRequestBean();
					bean.setType(matcher.group(1));
					bean.setUrl(matcher.group(2));
					bean.setHttpType(matcher.group(3));
					return bean;
				}
				return null;
			});
			this.requestBean=tbean;
		} catch (Exception e) {
			logger.error(StringUtils.isNullSetEmpty(this.request)+"转换错误", e);
		}
		
	}
	
	
}
